import {
  ref,
  isRef,
  shallowRef,
  nextTick,
  onMounted,
  onBeforeUnmount,
} from "vue";
import * as echarts from "echarts";

/* 
  使用如下：
  const [date, setDate] = useLocalStorage('date', '2023-10-15')

  直接使用数据
  <div>{{ date }}</div>

  更新数据
  setDate('2023-10-20')
*/
export const useLocalStorage = (key, defaultValue) => {
  let data;

  if (!key) {
    return null;
  }

  if (localStorage.getItem(key)) {
    data = ref(JSON.parse(localStorage.getItem(key)));
  }

  if (defaultValue) {
    localStorage.setItem(key, JSON.stringify(defaultValue));
    data = ref(defaultValue);
  }

  const update = (value) => {
    localStorage.setItem(key, JSON.stringify(value));
    if (isRef(data)) {
      data.value = value;
    } else {
      data = ref(value);
    }
  };

  return [data, update];
};

/* 
  使用同上
*/
export const useSessionStorage = (key, defaultValue) => {
  let data;

  if (!key) {
    return null;
  }

  if (sessionStorage.getItem(key)) {
    data = ref(JSON.parse(sessionStorage.getItem(key)));
  }

  if (defaultValue) {
    sessionStorage.setItem(key, JSON.stringify(defaultValue));
    data = ref(defaultValue);
  }

  const update = (value) => {
    sessionStorage.setItem(key, JSON.stringify(value));
    if (isRef(data)) {
      data.value = value;
    } else {
      data = ref(value);
    }
  };

  const remove = () => {
    sessionStorage.removeItem(key);
  };

  return [data, update, remove];
};

// echarts hook
export const useEcharts = (chartRef) => {
  const myChart = shallowRef(null);

  const resizeChart = () => {
    myChart.value.resize();
  };

  onMounted(() => {
    if (chartRef.value) {
      initEcharts();
    }
  });

  onBeforeUnmount(() => {
    if (myChart.value) {
      disposeEcharts();
    }
  });

  /**
   * 创建echarts实例 -- 避免某些子组件onMounted中还未加载echarts的dom
   * 例如:dialog
   */
  const initEcharts = () => {
    myChart.value = echarts.init(chartRef.value);
    window.addEventListener("resize", resizeChart);
  };

  // 销毁echarts实例 -- 同上
  const disposeEcharts = () => {
    window.removeEventListener("resize", resizeChart);
    myChart.value?.dispose();
    myChart.value = null;
  };

  const setOption = (option) => {
    nextTick(() => {
      myChart.value?.setOption(option);
    });
  };

  const getInstance = () => {
    return myChart.value;
  };

  const clearChart = () => {
    myChart.value?.clear();
  };

  return {
    setOption,
    resizeChart,
    getInstance,
    clearChart,
    echarts,
    myChart,
    initEcharts,
    disposeEcharts,
  };
};
